package com.ben.chatroom.processer;

import com.ben.chatroom.common.ProInstant;
import com.ben.chatroom.common.entity.ImUser;
import com.ben.chatroom.common.entity.ProtoMsg;
import com.ben.chatroom.protoBuilder.LoginResponseBuilder;
import com.ben.chatroom.session.LocalSession;
import com.ben.chatroom.session.SessionManage;
import org.springframework.stereotype.Service;

/**
 * @author huangyijun
 */
@Service
public class LoginProcessor implements ServerProcessor {

  @Override
  public ProtoMsg.HeadType op() {
    return ProtoMsg.HeadType.LOGIN_REQUEST;
  }

  @Override
  public boolean action(LocalSession session, ProtoMsg.Message msg) {
    long sequence = msg.getSequence();
    ProtoMsg.LoginRequest loginRequest = msg.getLoginRequest();
    ImUser user = ImUser.fromMsg(loginRequest);

    boolean isValid = checkUser(user);
    if(!isValid) {
      ProtoMsg.Message response = LoginResponseBuilder.loginResponse(ProInstant.ResultCode.NO_TOKEN, sequence, session.getSessionId());
      session.writeAndFlush(response);
      return false;
    }

    session.bind(user);
    SessionManage.inst().addLocalSession(session);

    ProtoMsg.Message response = LoginResponseBuilder.loginResponse(ProInstant.ResultCode.SUCCESS, sequence, session.getSessionId());
    session.writeAndFlush(response);

    return true;
  }


  /**
   * 校验用户
   */
  private boolean checkUser(ImUser user) {
    return true;
  }
}
